<template>
  <div class="workOrderFrom">
    <FixedOperation>
      <el-row>
        <el-col :span="4" :offset="20" class="flex justify-end">
          <slot></slot>
          <el-button
            @click="handleSave"
            type="primary"
            plain
            :disabled="unSave"
            v-if="isAdd || isFirst"
            >保存</el-button
          >
          <el-button
            @click="toProcessDetail"
            type="primary"
            plain
            v-if="ToProcess"
            >查看流程</el-button
          >
          <el-button
            @click="routerBack"
            type="primary"
            plain
            :disabled="unSave"
            v-if="backBtn"
            >返回</el-button
          >
          <el-button
            @click="process"
            type="primary"
            plain
            v-if="isAdd || isCanStart"
            >提交流程</el-button
          >
        </el-col>
      </el-row>
    </FixedOperation>
    <div class="app-container">
      <div class="part">
        <title-name
          title="工单基本信息"
          icon="i-carbon-bookmark-filled"
        ></title-name>
      </div>
      <el-form
        :model="baseForm"
        label-width="120px"
        :rules="rules"
        class="baseInfo"
        ref="baseWorkOrder"
      >
        <el-row>
          <el-col :offset="3" :span="9">
            <el-form-item label="工单主题:" prop="theme">
              <el-input
                v-model="baseForm.theme"
                placeholder="请输入工单主题"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item label="工单编码:" prop="num">
              <el-input
                v-model="baseForm.num"
                :readonly="true"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :offset="3" :span="9">
            <el-form-item label="工单级别:" prop="level">
              <el-radio-group v-model="baseForm.level" class="ml-4">
                <el-radio
                  v-for="item in work_order_level"
                  :label="item.value"
                  size="large"
                  >{{ item.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item></el-col
          >
          <el-col :span="9">
            <el-form-item label="工单类型:" prop="type">
              <el-tree-select
                v-model="baseForm.type"
                @change="changeType"
                placeholder="请选择业务分类"
                :data="workOrderType"
                default-expand-all
              /> </el-form-item
          ></el-col>
        </el-row>
        <el-row>
          <el-col :offset="3" :span="9">
            <el-form-item label="发起单位:" prop="发起单位">
              <div>
                {{
                  isAdd
                    ? org + ' ' + dept
                    : baseForm.companyName + ' ' + baseForm.deptName
                }}
              </div>
            </el-form-item></el-col
          >
          <el-col :span="9">
            <el-form-item label="发起人:" prop="发起人">
              <div>
                {{
                  isAdd
                    ? userStore.userInfo.nickName +
                      ' ' +
                      userStore.userInfo.phonenumber
                    : baseForm.sponsorName + ' ' + baseForm.sponsorPhone
                }}
              </div>
            </el-form-item></el-col
          >
        </el-row>
      </el-form>
      <div class="part">
        <title-name
          :title="`工单详细信息(${orderType})`"
          icon="i-carbon-bookmark-filled"
        ></title-name>
      </div>
      <el-form :model="detailForm" label-width="120px" ref="detailWorkorder">
        <el-row>
          <!-- 销售订单 -->
          <el-col :offset="3" :span="9" v-if="orderType === '售后工单'">
            <el-form-item
              label="客户名称:"
              prop="customerId"
              :rules="[
                {
                  required: true,
                  message: '请选择客户',
                  trigger: ['change', 'blur']
                }
              ]"
            >
              <el-input
                v-model="detailForm.customerIdCn"
                @focus="selectCustomer"
                clearable
                placeholder="请选择客户"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="9" v-if="orderType === '售后工单'">
            <el-form-item
              label="联系人/电话:"
              prop="customerPhone"
              :rules="[
                {
                  required: true,
                  message: '请填写联系人姓名及电话',
                  trigger: ['change', 'blur']
                }
              ]"
            >
              <el-input
                v-model="detailForm.customerPhone"
                placeholder="请输入联系人/电话"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :offset="3" :span="9" v-if="orderType === '售后工单'">
            <el-form-item label="关联订单:" prop="order">
              <el-input
                v-model="detailForm.linkOrderCn"
                @focus="selectOrder"
                clearable
                placeholder="请选择订单"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="9" v-if="orderType === '售后工单'">
            <el-form-item label="客户地址:" prop="customerAddress">
              <el-input
                v-model="detailForm.customerAddress"
                placeholder="请输入地址"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :offset="3" :span="9" v-if="orderType === '售后工单'">
            <el-form-item label="关联项目:" prop="project">
              <el-input
                v-model="detailForm.linkProjectCn"
                @focus="selectProject"
                clearable
                placeholder="请选择项目"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="9" v-if="orderType === '售后工单'">
            <el-form-item label="关联产品:" prop="product">
              <el-select
                v-model="detailForm.linkProduct"
                clearable
                placeholder="请选择产品"
              >
                <el-option
                  v-for="(item, index) in related_products"
                  :key="index"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 研发工单 -->
          <el-col :offset="3" :span="9" v-if="orderType === '研发工单'">
            <el-form-item
              label="系统/项目名称:"
              prop="projectName"
              :rules="[
                {
                  required: true,
                  message: '请选择系统/项目',
                  trigger: ['change', 'blur']
                }
              ]"
            >
              <el-autocomplete
                v-model="name"
                :fetch-suggestions="querySearch"
                clearable
                style="width: 100%"
                placeholder="系统/项目名称"
                @select="valueChange"
                @change="valueChange"
              />
              <!-- <el-select v-model="detailForm.projectName" clearable>
                <el-option
                  v-for="item in system_or_project_name"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select> -->
            </el-form-item>
          </el-col>
          <el-col :span="9" v-if="orderType === '研发工单'">
            <el-form-item
              label="期望完成时间:"
              prop="expectedEndTime"
              :rules="[
                {
                  required: true,
                  message: '请选择时间',
                  trigger: ['change', 'blur']
                }
              ]"
            >
              <el-date-picker
                v-model="detailForm.expectedEndTime"
                type="date"
                placeholder="选择时间"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <!--  -->
          <el-col :offset="3" :span="15">
            <el-form-item
              label="工单描述:"
              prop="details"
              :rules="[
                {
                  required: true,
                  message: '请输入工单内容描述',
                  trigger: ['change', 'blur']
                }
              ]"
            >
              <el-input
                type="textarea"
                placeholder="输入内容"
                :rows="7"
                maxlength="300"
                show-word-limit
                v-model="detailForm.details"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :offset="3" :span="15">
            <el-form-item label="附件:" prop="附件">
              <el-upload
                class="upload-demo"
                action="#"
                :http-request="handleFileChange"
                accept=".rar, .zip, .doc, .docx, .pdf"
                :show-file-list="false"
                :multiple="true"
                v-if="!unSave"
              >
                <el-button type="primary" style="font-size: 14px"
                  ><el-icon> <UploadFilled /> </el-icon>上传附件</el-button
                >
              </el-upload>
              <div
                class="text-14px"
                :class="{ 'mt-10px': !unSave }"
                style="width: 100%"
              >
                <div v-for="(item, index) in fileList" :key="item.fileId">
                  <a style="color: #409eff" :href="item.url">{{
                    item.origFileName
                  }}</a>
                  <el-button
                    text
                    plain
                    @click="delFileName(index)"
                    v-if="!unSave"
                    >删除</el-button
                  >
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!-- 客户弹出框 -->
    <SelectCustomer
      :dialog-param="formParams"
      @ok="selectCustomerData"
      @close="
        val => {
          formParams.isDialog = false
        }
      "
    ></SelectCustomer>
    <!-- 关联订单选择 -->
    <RelatedOrder
      :relatedParams="orderParams"
      @closeDialog="ordCloseDialog"
      @relatedOver="ordRelatedOver"
    />
    <!-- 关联项目 -->
    <RelatedProject
      :relatedParams="proParams"
      @closeDialog="proCloseDialog"
      @relatedOver="proRelatedOver"
    />
    <!-- 关联产品 -->
    <!-- <ProductDialog
      v-model="productParams.open"
      :dialogData="productParams"
      @getData="productRelatedOver"
    /> -->
    <!-- 流程 -->
    <submission-process
      :dialogParam="dialogParam"
      :flowOptions="flowOptions"
      @initiate="handleClose('initiate')"
      @close="handleClose('examine')"
    />
  </div>
</template>

<script setup>
import {
  work_order_type,
  work_order_level,
  system_or_project_name,
  related_products
} from '@/hooks/dict/business'
import useUserStore from '@/store/modules/user'
import useTagsViewStore from '@/store/modules/tagsView'
import { uploadFile, delFile } from '@/api/salesManage/contractManage'
import { treeselectNoPriv } from '@/api/rsgl/zzjg'
import { workOrderDetails, workOrderSave } from '@/api/rsgl/order'
import SubmissionProcess from '@/businessComponents/SubmissionProcess'
import {
  listProcess,
  getBusinessProStatus,
  getNodeData
} from '@/api/workflow/process'
import { getUserProfile } from '@/api/system/user'
const userStore = useUserStore()
const tagsView = useTagsViewStore()
const router = useRouter()
const { proxy } = getCurrentInstance()

const baseForm = ref({
  type: '1',
  level: '1',
  num: '系统自动生成工单编码',
  sponsorName: '',
  companyName: '',
  deptName: '',
  sponsorPhone: ''
})
const detailForm = ref({ customerType: 'customer' })
const rules = ref({
  theme: [
    { required: true, message: '请输入工单主题', trigger: ['change', 'blur'] }
  ],
  // num: [{ required: true }],
  level: [
    { required: true, message: '请选择工单级别', trigger: ['change', 'blur'] }
  ],
  type: [
    { required: true, message: '请选择工单类型', trigger: ['change', 'blur'] }
  ]
})
const route = useRoute()

const unSave = ref(false) //流程结束后 隐藏保存按钮
const proId = ref()
watch(
  () => route.query.id,
  val => {
    if (val) {
      proId.value = val
      getDtails(val)
    }
  },
  { deep: true, immediate: true }
)

const ToProcess = ref(false)
const backBtn = ref(false)
watch(
  () => route.query.procInsId,
  val => {
    if (val && !location.href.includes('workDetail')) {
      ToProcess.value = true
    } else {
      ToProcess.value = false
    }
    if (location.href.includes('workDetail')) {
      backBtn.value = true
    }
  },
  { deep: true, immediate: true }
)

// 跳转流程详情
function toProcessDetail() {
  router.push({
    path: '/process/workDetail',
    query: {
      procInsId: route.query.procInsId,
      //   taskId: row.taskId,
      processed: false
    }
  })
}

function routerBack() {
  tagsView.delView(router.currentRoute.value)
  router.back()
}

function getDtails(id) {
  workOrderDetails(id).then(res => {
    console.log(res)
    const resp = res.data
    // 流程判断
    if (resp.processState === '审批通过') {
      unSave.value = true
    }
    // 基本信息
    baseForm.value.theme = resp.theme
    baseForm.value.num = resp.num
    baseForm.value.level = resp.level
    baseForm.value.type = resp.type
    baseForm.value.fileNames = (resp.sysAttachFiles || []).map(v => v.fileName)
    baseForm.value.id = resp.id
    baseForm.value.sponsorName = resp.sponsorName
    baseForm.value.companyName = resp.companyName
    baseForm.value.deptName = resp.deptName
    baseForm.value.sponsorPhone = resp.sponsorPhone
    fileList.value = resp.sysAttachFiles
    // 详细信息
    changeType(baseForm.value.type)
    name.value = system_or_project_name.value.find(
      v => v.value == resp.workOrderExtVo.projectName
    )?.label
    detailForm.value.customerAddress = resp.workOrderExtVo.customerAddress
    detailForm.value.customerPhone = resp.workOrderExtVo.customerPhone
    detailForm.value.details = resp.workOrderExtVo.details
    detailForm.value.customerId = resp.workOrderExtVo.customerId
    detailForm.value.customerIdCn = resp.workOrderExtVo.customerIdCn
    detailForm.value.linkOrder = resp.workOrderExtVo.linkOrder
    detailForm.value.linkOrderCn = resp.workOrderExtVo.linkOrderCn
    detailForm.value.linkProduct = resp.workOrderExtVo.linkProduct
    detailForm.value.linkProject = resp.workOrderExtVo.linkProject
    detailForm.value.linkProjectCn = resp.workOrderExtVo.linkProjectCn
    detailForm.value.projectName = resp.workOrderExtVo.projectName
    detailForm.value.expectedEndTime = resp.workOrderExtVo.expectedEndTime
  })
}

const org = ref('')
const dept = ref('')
const formParams = ref({})
const isAdd = ref(true)
const isFirst = ref(false)
const postGroup = ref('')
// 获取初始化数据
async function initData() {
  // 获取发起人岗位
  getUserProfile().then(res => {
    console.log(res, '发起人')
    postGroup.value = res.postGroup
  })
  // 流程是否第一环节
  const id = route.query.id ? route.query.id : props.id
  const nodeData = await getNodeData(id)
  isFirst.value = nodeData.data === null || nodeData.data.isFirst === 'Y'
  // 是否新增页面
  isAdd.value = !!location.href.match(/addOrder/)
  console.log(isAdd.value, 'isAdd')
  if (isAdd.value) {
    // 获取发起人公司部门
    const list = await treeselectNoPriv()
    const orgObj = list.data[0].children.find(
      v => v.id === userStore.userInfo.orgId
    )
    org.value = orgObj?.label
    dept.value = orgObj.children.find(
      v => v.id === userStore.userInfo.deptId
    )?.label
  }

  // 客户参数赋值
  formParams.value = {
    type: 'customerId',
    customerType: 'customer',
    title: '客户选择',
    isDialog: false,
    multiple: false,
    nodeKey: 'id',
    tabVal: detailForm.value.customerType,
    defaultCheckedKeys: [],
    defaultCheckedLabel: []
  }
}
initData()

const workOrderType = computed(() => arrayToTree(ref(work_order_type).value)) // 工单类型树结构
const orderType = ref('普通工单')
function changeType(val) {
  const oldDetail = { ...detailForm.value }
  detailForm.value = {
    details: oldDetail.details
  }
  const findVal = ref(work_order_type).value.find(v => v.value === val)
  orderType.value = findVal.label
  if (findVal.parentId) {
    orderType.value = ref(work_order_type).value.find(
      v => v.value === findVal.parentId
    ).label
  }
}

// queryString 过滤下拉框
const querySearch = (queryString, cb) => {
  const results = queryString
    ? system_or_project_name.value.filter(createFilter(queryString))
    : system_or_project_name.value
  // call callback function to return suggestions
  const data = results.map(v => {
    return {
      value: v.label,
      label: v.value
    }
  })
  cb(data)
}

const createFilter = queryString => {
  return restaurant => {
    return restaurant.label.indexOf(queryString) !== -1
  }
}

const name = ref()
// 表单赋值businessName
function valueChange(val) {
  detailForm.value.projectName = system_or_project_name.value.find(
    v => v.label === val.value
  )?.value
}
//  选择客户名称
watch(
  () => detailForm.value.customerIdCn,
  (newVal, oldVal) => {
    // 清空关联信息
    if (!newVal) {
      // 联系人/电话
      detailForm.value.customerId = ''
      detailForm.value.customerPhone = ''
    }
    if (oldVal && newVal !== oldVal) {
      // 关联订单 关联项目
      detailForm.value.linkOrder = ''
      detailForm.value.linkOrderCn = ''
      detailForm.value.linkProject = ''
      detailForm.value.linkProjectCn = ''
    }
  }
)

function selectCustomer() {
  formParams.value.isDialog = true
  formParams.value.defaultCheckedKeys = detailForm.value.customerId
    ? [detailForm.value.customerId]
    : []
  formParams.value.defaultCheckedLabel = detailForm.value.customerIdCn
    ? [detailForm.value.customerIdCn]
    : []
}

function selectCustomerData(val) {
  console.log(val, 'selectCustomerData')
  if (
    val.selectData.length &&
    detailForm.value.customerId !== val.selectData[0].id
  ) {
    detailForm.value.customerPhone =
      val.selectData[0].mainContactName +
      '/' +
      val.selectData[0].mainContactPhone
    detailForm.value.customerId = val.selectData[0].id
    detailForm.value.customerIdCn = val.selectData[0].customerName
    detailForm.value.customerType = val.customerType
  }
}

// 关联订单
watch(
  () => detailForm.value.linkOrder,
  val => {
    if (!val) {
      detailForm.value.linkOrderCn = ''
    }
  }
)
const orderParams = ref({})
function selectOrder() {
  if (!detailForm.value.customerId) {
    proxy.$modal.msgError('请先选择客户')
    return
  }
  orderParams.value = {
    visible: true, // 显示dialog
    businessId: detailForm.value.customerId, // 根据id查询合同列表
    businessName: detailForm.value.customerIdCn,
    multiple: false, // 是否多选
    defaultSelect: detailForm.value.linkOrder // 默认选择数据
  }
}
function ordRelatedOver(val) {
  console.log(val, 'order')
  if (val && detailForm.value.linkOrder !== val.orderId) {
    detailForm.value.linkOrder = val.orderId
    detailForm.value.linkOrderCn = val.orderTitle
  }
  ordCloseDialog()
}
// 关闭弹窗
function ordCloseDialog() {
  orderParams.value.visible = false
}

// 关联项目

watch(
  () => detailForm.value.linkProject,
  val => {
    if (!val) {
      detailForm.value.linkProjectCn = ''
    }
  }
)
const proParams = ref({})
function selectProject() {
  if (!detailForm.value.customerId) {
    proxy.$modal.msgError('请先选择客户')
    return
  }
  proParams.value = {
    visible: true, // 显示dialog
    businessId: detailForm.value.customerId, // 根据id查询合同列表
    businessName: detailForm.value.customerIdCn,
    multiple: false, // 是否多选
    defaultSelect: detailForm.value.linkProject // 默认选择数据
  }
}
// 弹窗确认完成回调
function proRelatedOver(val) {
  console.log(val, '查看回调')
  if (val && detailForm.value.linkProject !== val.projectId) {
    detailForm.value.linkProject = val.projectId
    detailForm.value.linkProjectCn = val.proName
  }
  proCloseDialog()
}

// 关闭弹窗
function proCloseDialog() {
  proParams.value.visible = false
}

/****  关联产品  ****/
// const productParams = ref({})
// function selectProduct() {
//   productParams.value.open = true
//   productParams.value.productQuery = {
//     createUnit: userStore.userInfo.orgId, //产品所属单位
//     zeroExitControl: '1', //0库存出库
//     productFilter: 'y', //过滤所属板块
//     businessType: userStore.userInfo.businessSector.split(',') //所属板块
//   }
//   // productParams.value.comboQuery = {
//   //   deptId: userStore.userInfo.orgId //套餐所属单位
//   // }
// }

// function productRelatedOver(val) {
//   console.log(val)
// }

defineExpose({
  handleSave
})
const detailWorkorder = ref()
const baseWorkOrder = ref()
async function handleSave() {
  const base = await proxy.$refs.baseWorkOrder.validate()
  const detail = await proxy.$refs.detailWorkorder.validate()
  return new Promise((resolve, reject) => {
    try {
      if (base && detail) {
        baseForm.value.fileNames = (fileList.value || []).map(v => v.fileName)
        baseForm.value.sponsorId = userStore.userInfo.userId
        if (isAdd.value) {
          // 新增时删除baseForm.num
          !unSave.value && delete baseForm.value.num
        } else {
          // 删除发起人 发起单位
          // delete baseForm.value.sponsorName
          // delete baseForm.value.companyName
          // delete baseForm.value.deptName
          // delete baseForm.value.sponsorPhone
          delete baseForm.value.sponsorId
        }
        workOrderSave({
          ...baseForm.value,
          workOrderExtVo: { ...detailForm.value }
        })
          .then(res => {
            isAdd.value
              ? proxy.$modal.msgSuccess('保存成功')
              : proxy.$modal.msgSuccess('修改成功')
            if (isAdd.value) {
              // 新增成功关闭标签页，跳回列表页
              // tagsView.delView(router.currentRoute.value)
              // router.push('workOrder')
              unSave.value = true
              getDtails(res.msg)
            } else {
              getDtails(baseForm.value.id)
            }
            resolve(res.msg)
          })
          .catch(err => {
            reject(err)
          })
      }
    } catch (error) {
      console.log(error)
    }
  })
}

// 上传前检查文件类型大小
function beforeUpload(rawFile) {
  const type = rawFile.name.substring(rawFile.name.lastIndexOf('.'))
  const allowType = ['.rar', '.zip', '.doc', '.docx', '.pdf'].indexOf(type) < 0
  if (allowType) {
    proxy.$message.error('上传文件只能是rar、zip、doc、docx、pdf格式!')
    return
  }
  if (rawFile.size / 1024 / 1024 > 20) {
    proxy.$modal.msgError('单个文件不能超过20MB!')
    return false
  }
}

const fileList = ref([])
// 上传方法
async function handleFileChange(params) {
  const type = params.file.name.substring(params.file.name.lastIndexOf('.'))
  const allowType = ['.rar', '.zip', '.doc', '.docx', '.pdf'].indexOf(type) < 0
  if (allowType) {
    proxy.$message.error('上传文件只能是rar、zip、doc、docx、pdf格式!')
    return
  }
  if (params.file.size / 1024 / 1024 > 20) {
    proxy.$modal.msgError('单个文件不能超过20MB!')
    return false
  }
  let formData = new FormData()
  formData.append('file', params.file)
  try {
    const res = await uploadFile(formData)
    if (res.code === 200 && res.data) {
      fileList.value.push(res.data)
    } else {
      console.log(res.msg)
    }
  } catch (error) {
    console.error(error)
  }
}

// 删除文件
async function delFileName(index) {
  try {
    proxy.$modal.confirm('是否删除该文件').then(async () => {
      const file = fileList.value[index]
      const res = await delFile(file.fileName)
      if (res.code === 200) {
        fileList.value.splice(index, 1)
        proxy.$modal.msgSuccess(res.data)
      }
    })
  } catch (error) {
    console.log(error)
  }
}

/****   流程   ****/
const dialogParam = ref({})
const isCanStart = ref(false) // 判断该业务是否可以审批发起 以及办理详情 访问的时候不能审批 ===》针对编辑页面  办理详情面  办理详情
const isExamine = ref(false)
const projectId = ref()
const proInsId = ref()
const isSave = ref()
const props = defineProps({
  id: {
    type: String
  }
})

const flowOptions = ref([]) //该业务的流程数据
const initFlowFn = async type => {
  // 1.查询该业务是否有流程
  let comRes = await listProcess({ pageNum: 1, pageSize: 9999, category: type })
  flowOptions.value = comRes.rows
  // 2.根据
  if (!flowOptions.value || JSON.stringify(flowOptions.value) == '[]') {
    console.log('未建流程')
    //2.1 没有流程-提示不能新建数据
    proxy.$modal.msgError('该业务没有流程，不能新建')
    handleBack()
  } else if (flowOptions.value.length == 1) {
    console.log('1条流程')
    //2.2 流程只有一个，只有一条流程时，则不弹出框流程提交审核按钮隐藏，直接点击保存
    isExamine.value = false
  } else {
    //2.3多条流程时
  }
}

const getBusinessProStatusFn = async () => {
  let statusRes = await getBusinessProStatus({ businessId: projectId.value })
  console.log(statusRes, 'statusRes')
  if (statusRes.data.canStart) {
    // canStart false时 不能发起，true则可以发起
    console.log(111112, 'canStart')
    isCanStart.value = true
    initFlowFn(26) //业务类型==>流程分类 页面查看
  } else {
    isCanStart.value = false
  }
}

watch(
  () => props.id,
  val => {
    if (location.href.match(/editOrder/)) {
      console.log('edit')
      //编辑页面---------------
      projectId.value = val || route.query.id
      proInsId.value = route.query.proInsId
      // init()
      isSave.value = true
      //根据业务查询审批状态
      getBusinessProStatusFn()
    } else if (
      (val && !!location.href.match(/detail/)) ||
      (val && !!location.href.match(/workDetail/))
    ) {
      console.log('detail or workDetail')
      // 待办详情-访问--------------------
      projectId.value = val
      dialogParam.value.businessId = val
      // init()
      getDtails(val)
      isSave.value = true
      isCanStart.value = false
      isFirst.value = false
    } else if (location.href.match(/addOrder/)) {
      console.log('add')
      // 新建页面 ---------------
      // 走业务流程
      initFlowFn(26)
      isExamine.value = true
      // init()
    }
  },
  {
    immediate: true
  }
)

async function process() {
  let id
  console.log('user', userStore)
  try {
    // 提交流程前先执行一次保存操作
    id = await handleSave()
    if (id) {
      dialogParam.value.visible = true
      dialogParam.value.businessId = id
      dialogParam.value.businessName = baseForm.value.theme + '的工单流程'
      dialogParam.value.categoryCode = '26'
      // 判断岗位是否为部门领导
      dialogParam.value.isLeader = postGroup.value.includes('部门经理')
      // dialogParam.value.completion = '办结'
      // dialogParam.value.otherApprovals = '提交分管领导'
    }
  } catch (error) {
    console.log(error)
  }
}

const handleClose = type => {
  switch (type) {
    case 'examine':
      //弹出框关闭
      dialogParam.value.visible = false
      break
    case 'initiate':
      //审批 发起成功-关闭当前路由
      dialogParam.value.visible = false
      handleBack()
      break
  }
}
// 返回handleBack
const handleBack = () => {
  tagsView.delView(router.currentRoute.value)
  router.go(-1)
}
// 数组转换树
/**
 * @params arr 输入数组
 * @params nodeKey 树唯一标识
 * @params parentId 父id
 *
 */
function arrayToTree(arr, nodeKey = 'value', parentId = 'parentId') {
  const mapObj = new Map()
  const result = []
  arr.forEach(v => {
    mapObj.set(v.value, v)
  })
  for (const [key, val] of mapObj) {
    if (val.parentId && mapObj.has(val.parentId)) {
      if (!mapObj.get(val.parentId).children) {
        mapObj.get(val.parentId).children = []
      }
      const some = mapObj.get(val.parentId).children.some(v => {
        return v.value === val.value
      })
      if (!some) {
        mapObj.get(val.parentId).children.push(val)
      }
    } else {
      result.push(mapObj.get(key))
    }
  }
  return result
}
</script>

<style scoped lang="scss">
.workOrderFrom {
  .part {
    @apply mb-20px;
  }
  :deep(.el-select) {
    width: 100%;
  }
}
</style>
